<?php

namespace App\Models;

use Encore\Admin\Traits\AdminBuilder;
use Encore\Admin\Traits\ModelTree;
use Illuminate\Database\Eloquent\Model;

class BrandSort extends Model
{
    use ModelTree, AdminBuilder;

    protected $table = 'c_brand_sorts';

    protected $fillable = ['pid', 'brand_name', 'sort'];

    protected $with = [
        'parent'
    ];


    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        $this->setParentColumn('pid');  // 父ID
        $this->setOrderColumn('sort'); // 排序
        $this->setTitleColumn('brand_name'); // 标题
        $this->setParentColumn('pid');//删除使用的pid
    }

    /**
     * 该分类的子分类
     */
    public function child()
    {
        return $this->hasMany(get_class($this), 'pid', $this->getKeyName());
    }

    /**
     * 该分类的父分类
     */
    public function parent()
    {
        return $this->hasOne(get_class($this), $this->getKeyName(), 'pid');
    }
    /**
     * 获取下拉列表
     * @return array
     */
    public function getOptions()
    {
        $options = $this->select('id', 'brand_name as text')->get();
        $selectOption = [];
        foreach ($options as $option) {
            $selectOption[$option->id] = $option->text;
        }
        return $selectOption;
    }
    /**获取分类名称
     * @param $id
     * @return mixed
     */
    public function getName($id)
    {
        $res =  $this->select('brand_name')->find($id);
        if(!empty($res)){
            return $res->brand_name;
        }else{
            return '';
        }
    }
}
